<template>
  <div class="allDiv">
  <el-card>
  <div slot="header" class="clearfix relative ">
       <span class="title-icon">详细地址管理</span>
  </div>
  <div class="mainDiv">
    <el-form ref="elForm" :model="formData" :rules="rules" size="small" label-width="100px">
      <el-form-item label="英文地址1：" prop="addressLine1">
        <el-input v-model="formData.addressLine1" placeholder="请输入英文地址1"  :maxlength="35" clearable
          prefix-icon='el-icon-s-home' class="otherInput" :disabled=inputDisabled></el-input>
      </el-form-item>
      <el-form-item label="英文地址2：" prop="addressLine2">
        <el-input v-model="formData.addressLine2" placeholder="请输入英文地址2"  :maxlength="35" clearable
          prefix-icon='el-icon-s-home' class="otherInput" :disabled=inputDisabled></el-input>
      </el-form-item>

      <el-form-item label="国家：" prop="countryCode" >
        <el-select v-model="formData.countryCode" placeholder="请选择国家"  class="selectInput" :disabled=inputDisabled>
                    <el-option
                      v-for="(item, code) in optionsMap"
                      :key="code"
                      :label="item"
                      :value="code"
                    />
        </el-select>
        <i style="font-style:normal;margin-left: 10px;color: red;" v-if="formData.countryCode && ['US', 'CA'].includes(formData.countryCode)">对接AMS</i>
      </el-form-item>

      <el-form-item
          v-if="formData.countryCode && ['US', 'CA','AU'].includes(formData.countryCode)"
          label="州/省："
          prop="stateOrRegion"
          :disabled=inputDisabled
        >
          <el-select v-model="formData.stateOrRegion" filterable placeholder="请选择州/省" class="selectInput" :disabled=inputDisabled>
            <el-option
              v-for="item in stateMap[formData.countryCode]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-else prop="stateOrRegion" class="otherInput" :disabled=inputDisabled>
          <div slot="label">州/省：</div>
          <el-input
            v-model="formData.stateOrRegion"
            :maxlength="textLength"
            placeholder="请填写州/省"
            :disabled=inputDisabled
          />
        </el-form-item>
      <el-form-item label="城市：" prop="cityName" class="otherInput" >
        <el-input v-model="formData.cityName" placeholder="请输入城市" :disabled=inputDisabled>
        </el-input>
      </el-form-item>
      <el-form-item label="邮编：" prop="postalCode" class="otherInput">
        <el-input v-model="formData.postalCode"  placeholder="请输入邮编" :disabled=inputDisabled>
        </el-input>
      </el-form-item>
      <el-form-item size="large">
        <el-button type="primary" size="mini" icon="el-icon-edit" @click="update" class="button">{{updateMes}}</el-button>
        <el-button type="primary" size="mini" icon="el-icon-success" @click="submitForm" class="button">提交</el-button>
        <el-button type="primary" size="mini" icon="el-icon-warning-outline" @click="resetForm" class="button">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
  </el-card>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import { getStateByCode } from '@/utils/getStateByCode';
export default {
  data() {
    return {
      inputDisabled: true,
      updateMes: '修改',
      stateMap: getStateByCode(),
      optionsMap:{},
      formData: {
        id: "",
        addressLine1: "",
        addressLine2: "",
        countryCode: "",
        stateOrRegion: "",
        cityName: "",
        postalCode: "",
      },
      rules: {
        addressLine1: [],
        addressLine2: [],
        countryCode: [],
        stateOrRegion: [],
        cityName: [],
        postalCode: [],
      },
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
        this.init();
        const _this = this
        // 美国特定邮编
        this.rules.postalCode = [
          {
            validator: (rule, value, cb) => {
              const reg1 = /^((\d{5})*(-\d{4})|(\d{5}))$/;
              if (
                value !==""&&
                ['US'].includes(_this.formData.countryCode)&&
                !reg1.test(value)
              ) {
                cb(new Error('格式错误，美国邮编请填入XXXXX或者XXXXX-XXXX'))
              } else {
                cb()
              }
            },
            trigger: 'blur',
          },
        ],
        this.rules.addressLine1= [
          {
            validator: (rule, value, cb) => {
              const cnReg = new RegExp(
                '([\u4e00-\u9fa5])+',
                'g'
              )
              if (
                !['CN', 'JP'].includes(_this.formData.countryCode)
                &&
                cnReg.test(value)
              ) {
                cb(new Error('目的国非中国/日本，禁用中文'))
              }else{
                cb()
              }
            },
            trigger: 'blur',
          },
        ],
        this.rules.addressLine2= [
          {
            validator: (rule, value, cb) => {
              const cnReg = new RegExp(
                '([\u4e00-\u9fa5])+',
                'g'
              )
              if (
                !['CN', 'JP'].includes(_this.formData.countryCode)
                &&
                cnReg.test(value)
              ) {
                cb(new Error('目的国非中国/日本，禁用中文'))
              }else{
                cb()
              }
            },
            trigger: 'blur',
          },
        ],
        this.rules.cityName= [
          {
            validator: (rule, value, cb) => {
              const cnReg = new RegExp(
                '([\u4e00-\u9fa5])+',
                'g'
              )
              if (
                !['CN', 'JP'].includes(_this.formData.countryCode)
                  &&
                cnReg.test(value)
              ) {
                cb(new Error('目的国非中国/日本，禁用中文'))
              }else{
                cb()
              }
            },
            trigger: 'blur',
          },
        ],
        this.rules.stateOrRegion= [
          {
            validator: (rule, value, cb) => {
              const cnReg = new RegExp(
                '([\u4e00-\u9fa5])+',
                'g'
              )
              if (
                !['CN', 'JP'].includes(_this.formData.countryCode)
                  &&
                cnReg.test(value)
              ) {
                cb(new Error('目的国非中国/日本，禁用中文'))
              }else{
                cb()
              }
            },
            trigger: 'blur',
          },
        ]
  },
  methods: {
    async init() {
      this.optionsMap=this.$store.state.blank.entry.sources["countryCodeSource"];
      this.formData.id = parseInt(this.$route.query.pid);
      ajax("findByObjectId",{"id":this.formData.id},{
        class: "com.tofba.app.client.setting.ServeCompanyClient"
      }).then(
        res => {
          if (res.code == 200) {
            debugger
            this.formData=res.data;
            debugger
          } else {
            this.$message.error("数据异常");
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    submitForm() {
        this.$refs['elForm'].validate(valid => {
          if (!valid) return
          this.submitUpdate();
        })
    },
    submitUpdate() {
      if(this.inputDisabled===false){
      ajax("updateAddress", this.formData, {
        class: "com.tofba.app.client.setting.ServeCompanyClient"
      }).then(
        res => {
          if (res.code == 200) {
              this.$message({
                   message: "保存成功",
                   type: "success"
              });
              this.init();
              this.inputDisabled=true;
              this.updateMes='修改';
          } else {
            this.$message.error("数据异常");
            this.init();
            this.inputDisabled=true;
            this.updateMes='修改';
          }
        },
        error => {
          console.log(error);
        }
      );
      }
    },

    update(){
      if(this.inputDisabled===true){
         this.inputDisabled=false
         this.updateMes='取消'
      }else{
         this.init();
         this.inputDisabled=true
         this.updateMes='修改'
      }
    },
    resetForm() {
      if(this.inputDisabled===false){
        this.$refs['elForm'].resetFields()
      }
    },
  }
}
</script>

<style>
 .allDiv{
    width: 950px;
    margin-left: 450px;
    margin-top: 50px;
 }
 .mainDiv{
    width: 800px;
    margin-top: 10px;
    margin-left: 100px;
    height: 400px;
 }
 .otherInput{
    width: 550px;
 }
 .selectInput{
    width: 450px;
 }
 .button{
    margin-top: 20px;
    margin-left: 100px;
    margin-right: 20px;
 }
</style>
